loglike.cohort.fn <- function(N0,F, M, q.s, E.s, catch.sel.pars, survey.sel.pars, intervals, F.ind, catch, survey){

	n_intervals <- length(intervals)
	age <- cumsum(intervals) - intervals/2
#	print(age)
#	print(catch.sel.pars)
	F <- F*sel.fn(age, catch.sel.pars)*F.ind
	survey.F <- q.s * E.s * sel.fn(age, survey.sel.pars)
	hazard <-  M + survey.F + F
	s <- exp(-hazard*intervals)
#	print(survey.F)
#	print(hazard)
#	print((1-s)*survey.F/hazard)
	p.c <- (1-s)*F/hazard
	p.s <- (1-s)*survey.F/hazard
	pmats <-array(0, dim = c(4,4,n_intervals))
	pmats[1,1,] <- s
	pmats[1,2,] <- p.c
	pmats[1,3,] <- p.s
	pmats[1,4,] <- (1-s)*M/hazard
	pmats[2,2,] <- pmats[3,3,] <- pmats[4,4,] <- 1
	
	cumpmats <- array(0, dim = c(4,4,n_intervals))
	for(i in 1:length(intervals)){
		if(i == 1) cumpmats[,,i] <- pmats[,,i]
		else cumpmats[,,i] <- cumpmats[,,i-1]%*% pmats[,,i]
	}
#	print(pmats)
	#print(cumpmats)
	print(sum(c(1,cumpmats[1,1,-dim(cumpmats)[3]])*pmats[1,2,]) + sum(c(1,cumpmats[1,1,-dim(cumpmats)[3]])*pmats[1,3,]) +
	sum(cumpmats[1,c(1,4),dim(cumpmats)[3]]))
	loglike.c <- catch * (log(c(1,cumpmats[1,1,-n_intervals])) + log(pmats[1,2,]))
	print(loglike.c)
	loglike.s <- (survey * (log(c(1,cumpmats[1,1,-n_intervals])) + log(pmats[1,3,])))[E.s > 0] #remove NAs due to zero probability
	print(loglike.s)
	loglike.else <- (N0) * log(sum(cumpmats[1,c(1,4),n_intervals]))
	print(loglike.else)
	print(lfactorial(N0))
	print(sum(lfactorial(survey)))
	print(sum(lfactorial(catch)))
	print(sum(loglike.c))
	print(sum(loglike.s))
	print(sum(loglike.else))
	print(sum(loglike.c,loglike.s,loglike.else))
	print(lfactorial(N0+sum(survey)+sum(catch)) - sum(lfactorial(survey)) - sum(lfactorial(catch)) - lfactorial(N0))
	loglike <- lfactorial(N0+sum(survey)+sum(catch)) - sum(lfactorial(survey)) - sum(lfactorial(catch)) - lfactorial(N0) + sum(loglike.c,loglike.s,loglike.else)
	return(loglike)
}
#loglike.cohort.fn(F = rep(0.3,12), M = rep(0.2, 12), q.s = 0.3, 
#	E.s = rep(c(0.05,0.05,0.05,rep(0,9))), survey.sel.pars = c(5,2), catch.sel.pars = c(1,5),
#	intervals = rep(1/12,12), F.ind = rep(1,12), catch = catches[,1], survey = surveys[,1])
